//package com.itisyue.fun.controller;
//import com.itisyue.fun.service.FileService;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.core.io.FileSystemResource;
//import org.springframework.core.io.Resource;
//import org.springframework.http.HttpHeaders;
//import org.springframework.http.HttpStatus;
//import org.springframework.http.ResponseEntity;
//import org.springframework.util.StringUtils;
//import org.springframework.web.bind.annotation.GetMapping;
//import org.springframework.web.bind.annotation.RequestHeader;
//import org.springframework.web.bind.annotation.RequestParam;
//import org.springframework.web.bind.annotation.RestController;
//
//import javax.servlet.http.HttpServletResponse;
//import java.io.File;
//import java.io.IOException;
//
//import org.springframework.http.HttpRange; // 核心类
//import org.springframework.web.server.ResponseStatusException;
//
//import java.nio.channels.Channels;
//import java.nio.channels.FileChannel;
//import java.nio.channels.WritableByteChannel;
//import java.nio.file.Files;
//import java.nio.file.Path;
//import java.nio.file.Paths;
//import java.nio.file.StandardOpenOption;
//import java.util.List;
//@Slf4j
//@RestController
//public class FileControllerV2 {
//    private static final int DEFAULT_CHUNK_SIZE = 1 * 1024 * 1024; // 默认分块大小2MB
//
//    @Autowired
//    private FileService fileService;
//
//    @GetMapping("/file")
//    public ResponseEntity<Resource> downloadFile(
//            @RequestParam String filePath,
//            @RequestHeader(value = HttpHeaders.RANGE, required = false) String rangeHeader,
//            HttpServletResponse response) throws IOException {
//
//        // 1. 验证文件合法性
//        File file = validateFile(filePath);
//        long fileSize = file.length();
//
//        // 2. 设置通用响应头
//        response.setHeader(HttpHeaders.ACCEPT_RANGES, "bytes");
//        response.setHeader("X-Accel-Buffering", "no");
//
//        // 3. 处理Range请求（206 Partial Content）
//        if (StringUtils.hasText(rangeHeader) && rangeHeader.startsWith("bytes=")) {
//            return handleRangeRequest(file, rangeHeader, fileSize, response);
//        }
//
//        // 4. 完整文件请求（200 OK）
//        return ResponseEntity.ok()
//                .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"" + file.getName() + "\"")
//                .header(HttpHeaders.CONTENT_TYPE, "application/octet-stream")
//                .header(HttpHeaders.CONTENT_LENGTH, String.valueOf(fileSize))
//                .body(new FileSystemResource(file));
//    }
//
//    // 处理范围请求的核心方法
//    private ResponseEntity<Resource> handleRangeRequest(File file, String rangeHeader,
//                                                        long fileSize, HttpServletResponse response) throws IOException {
//
//        // 1. 解析Range头
//        HttpRange httpRange = parseRangeHeader(rangeHeader, fileSize);
//        long start = httpRange.getRangeStart(fileSize);
//        long end = httpRange.getRangeEnd(fileSize);
//        long contentLength = end - start + 1;
//
//        // 2. 设置范围响应头
//        response.setStatus(HttpStatus.PARTIAL_CONTENT.value());
//        response.setHeader(HttpHeaders.CONTENT_RANGE, "bytes " + start + "-" + end + "/" + fileSize);
//        response.setHeader(HttpHeaders.CONTENT_LENGTH, String.valueOf(contentLength));
//
//        // 3. 使用NIO零拷贝传输（关键优化点）
//        try (FileChannel channel = FileChannel.open(file.toPath(), StandardOpenOption.READ)) {
//            WritableByteChannel outputChannel = Channels.newChannel(response.getOutputStream());
//            channel.transferTo(start, contentLength, outputChannel);
//        }
//
//        return ResponseEntity.status(HttpStatus.PARTIAL_CONTENT).build();
//    }
//
//    // 解析Range头方法（基于Spring HttpRange）
//    private HttpRange parseRangeHeader(String rangeHeader, long fileSize) {
//        List<HttpRange> ranges = HttpRange.parseRanges(rangeHeader);
//        if (ranges.isEmpty() || ranges.size() > 1) {
//            throw new IllegalArgumentException("Invalid Range Header");
//        }
//        HttpRange range = ranges.get(0);
//        if (range.getRangeEnd(fileSize) >= fileSize) {
//            throw new IllegalArgumentException("Range exceeds file size");
//        }
//        return range;
//    }
//
//    // 文件验证方法
//    private File validateFile(String filePath) {
//        Path path = Paths.get(filePath).normalize();
//        if (!Files.exists(path) || Files.isDirectory(path)) {
//            throw new ResponseStatusException(HttpStatus.NOT_FOUND, "File not found");
//        }
//        return path.toFile();
//    }
//}